package com.ruoyi.web.controller.tool.dataManage;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.db.DSqlKit;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/dataManage/dataSet")
public class DataSetController extends BaseController {
    @ResponseBody
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody(required = false) Map<String,Object> data)
    {
        Integer pageIndex = 1;
        Integer pageSize = 20;
        if(data!=null)
        {
            if(data.get("pageNum")!=null)
            {
                pageIndex = Integer.parseInt(data.get("pageNum").toString());
            }
            if(data.get("pageSize")!=null)
            {
                pageSize = Integer.parseInt(data.get("pageSize").toString());
            }
        }
        String select="select * ";
        DSqlKit.init(" from sys_data_set where pid='-1' ");
        if(!ObjectUtils.isEmpty(data.get("name")))
        {
            String val = "%" +data.get("name").toString()+ "%";
            DSqlKit.append(" and (name like ?) ", val);
        }
        if(!ObjectUtils.isEmpty(data.get("code")))
        {
            String val = "%" +data.get("code").toString()+ "%";
            DSqlKit.append(" and (code like ?) ", val);
        }

        if(!ObjectUtils.isEmpty(data.get("type")))
        {
            DSqlKit.append(" and (type = ?) ", data.get("type").toString());
        }

        if(!ObjectUtils.isEmpty(data.get("status")))
        {
            DSqlKit.append(" and (status = ?) ", data.get("status").toString());
        }
        DSqlKit.append(" order by  create_time desc ");
        System.out.println(DSqlKit.getSql());
        List<Record> test=Db.find(select+DSqlKit.getSql());
        Page<Record> page =  Db.paginate(pageIndex, pageSize,select,DSqlKit.getSql(),DSqlKit.getParamList());
        return getDataTable(page);
    }


    @RequestMapping(value = "/getInfo/{id}" ,method = RequestMethod.GET)
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        Map<String, Object> returnMap=new HashMap<>();
        if(id!=null)
        {
            if(id.equals("add"))//新增
            {
                return AjaxResult.success(returnMap);
            }
            else
            {
                return AjaxResult.success(getTeedata(id));
            }
        }
        else
        {
            return AjaxResult.error("必要入参不能为空！");
        }
    }


    /**
     * 递归获取树形结构结构
     * @param id
     * @return
     */
    public static Map<String,Object> getTeedata(String id)
    {
        Map<String, Object> returnMap=new HashMap<>();
        Record data=Db.findFirst("select * from sys_data_set where id=?",id);
        if(data!=null)
        {
            data.set("topic",data.getStr("name"));
            returnMap=data.getColumns();
            List<Record> ListChildren=Db.find("select * from sys_data_set where pid=?",id);
            if(ListChildren.size()>0)
            {
                List<Map<String,Object>> childrenList=new ArrayList<>();
                for(Record childrenData:ListChildren)
                {
                    String childrenId=childrenData.getStr("id");
                    childrenList.add(getTeedata(childrenId));
                }
                returnMap.put("children",childrenList);
            }
        }
        return returnMap;
    }
    @RequestMapping(value = "/{id}" ,method = RequestMethod.GET)
    public AjaxResult getDataSetInfo(@PathVariable("id") String id)
    {
        Map<String, Object> returnMap=new HashMap<>();
        if(id!=null)
        {
            Record data=Db.findFirst("select * from sys_data_set where id=?",id);

            if(data!=null)
            {
                Map<String,Object> returnData=data.getColumns();
                List<Record> parameterList=Db.find("select * from sys_data_set_parameter where set_id=? order by sort",id);
                returnData.put("parameters",com.ruoyi.common.db.RecordUtil.RecordListToMapList(parameterList));
                List<Record> fieldList=Db.find("select * from sys_data_set_field where set_id=?",id);
                returnData.put("fields",com.ruoyi.common.db.RecordUtil.RecordListToMapList(fieldList));
                return AjaxResult.success(data.getColumns());
            }
            else
            {
                return AjaxResult.error("查询不到数据！");
            }
        }
        else

        {
            return AjaxResult.error("必要入参不能为空！");
        }
    }
    @ResponseBody
    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody(required = true) Map<String,Object> data) throws Exception {
        Map<String,Object> returnData=new HashMap<>();
        String key="";
        Record saveData=new Record();
        saveData.setColumns(data);
        Boolean flag=Db.tx(() -> {
            String guid=UUID.randomUUID().toString();
            saveData.set("update_time",new Date());
            List<Map<String,Object>> parameterList=saveData.get("parameters");
            saveData.remove("parameters");
            saveData.remove("fields");
            if(data.get("id")!=null)
            {
                saveData.remove("create_time");
                saveData.set("update_time",new Date());
                Db.update("sys_data_set",saveData);
                guid=saveData.get("id").toString();
            }
            else
            {
                saveData.set("id",guid);
                saveData.set("create_time",new Date());
                saveData.remove("updateTime");
                saveData.remove("createTime");
                Db.save("sys_data_set",saveData);
            }
            Db.update("delete from sys_data_set_parameter where set_id=?",guid);
            for(Map<String,Object> parame:parameterList)
            {
                Record newParame=new Record();
                newParame.setColumns(parame);
                newParame.set("id",UUID.randomUUID().toString());
                newParame.set("set_id",guid);
                newParame.remove("createTime");
                newParame.remove("updateTime");
                newParame.remove("setId");
                Db.save("sys_data_set_parameter",newParame);
            }
            return true;
        });
        if(flag)
        {
            returnData.put("code","200");
            returnData.put("data",saveData.getColumns());
            returnData.put("msg","保存成功");
        }
        else {
            returnData.put("code","500");
            returnData.put("msg","保存失败！");
        }
        return returnData;
    }


    @RequestMapping(value = "/test/{id}" ,method = RequestMethod.GET)
    public AjaxResult testDataSet(@PathVariable("id") String id) throws Exception {
        Map<String,Object> returnMap=new HashMap<>();
        Record dataSet=Db.findFirst("select * from sys_data_set where id=?",id);
        if(dataSet!=null)
        {
            String setCode=dataSet.getStr("code");
            String setType=dataSet.getStr("type");
            String setSQl=dataSet.getStr("SQL");
            if(setType.equals("object"))
            {
                SqlPara sp=new SqlPara();
                sp.setSql(setSQl);
                List<Record> parameList=Db.find("select * from sys_data_set_parameter where set_id=? order by sort",id);
                for(Record data:parameList)
                {
                    sp.addPara(data.get("default"));
                }
                Record rentunData=Db.use("peisSystem").findFirst(sp);

                returnMap.put(setCode,rentunData.getColumns());
            }
            if(setType.equals("array"))
            {
                SqlPara sp=new SqlPara();
                sp.setSql(setSQl);
                List<Record> parameList=Db.find("select * from sys_data_set_parameter where set_id=? and status='0' order by sort",id);
                for(Record data:parameList)
                {
                    sp.addPara(data.get("default"));
                }
                List<Record> rentunList=Db.use("peisSystem").find(sp);
                List<Map<String,Object>> dataListMap=new ArrayList<>();
                for(Record rc:rentunList)
                {
                    dataListMap.add(rc.getColumns());
                }

                returnMap.put(setCode,dataListMap);
            }
            return AjaxResult.success(returnMap);
        }
        else
        {
            return AjaxResult.error("未找到数据集！");
        }
    }


    @RequestMapping(value = "/getDataSetByParameter" ,method = RequestMethod.POST)
    public AjaxResult getDataSetByParameter(@RequestBody(required = true) Map<String,Object> data)
    {
        if(data.get("id")==null)
        {
            return AjaxResult.error("数据集主键参数缺失！");
        }
        Map<String,Object> parameter=new HashMap<>();
        if(data.get("parameter")!=null)
        {
            parameter=(Map<String,Object>)data.get("parameter");
        }
        Map<String,Object> returrnMap=DataSetUtil.getDataSetRoot(data.get("id").toString(),parameter);
        if(returrnMap.get("code").equals("200"))
        {
            return AjaxResult.success(returrnMap);
        }
        else {
            return AjaxResult.error(returrnMap.get("msg").toString());
        }
    }


    @RequestMapping(value = "/testAll/{id}" ,method = RequestMethod.GET)
    public AjaxResult testAllDataSet(@PathVariable("id") String id) throws Exception {
        return AjaxResult.success(DataSetUtil.getDataSetRoot(id));
    }




    /**
     * 删除在线客服咨询问题
     */

    @Log(title = "删除数据集", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/delete/{ids}" ,method = RequestMethod.GET)
    public AjaxResult remove(@PathVariable String[] ids)
    {
//        String idstr= ArrayUtils.toString(ids, ",").replace("{","").replace("}","").replace(",","','");
        Boolean flage=true;
        for(String id:ids)
        {
            flage=deleteAll(id);
            if(!flage)
            {
                break;
            }
        }

        if(flage)
        {
            return AjaxResult.success("删除成功！");
        }
        else
        {
            return AjaxResult.error("删除失败！");
        }
    }

    /**
     * 递归删除所有子集
     * @return
     */
    public boolean deleteAll(String id)
    {
        Boolean flage=Db.tx(()->{
            List<Record> list=Db.find("select * from sys_data_set where pid=?",id);
            if(list.size()>0)
            {
                for (Record data:list)
                {
                    deleteAll(data.getStr("id"));
                }
            }
            Db.deleteById("sys_data_set",id);
            return true;
        });
        return flage;
    }


}
